<?php
namespace App\Http\Controllers;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use App\Models\Agent;
use App\Models\Mem;
use App\Models\Set;
use App\Models\Channel;
use App\Models\FeeItem;
use App\Models\GoodItem;
use App\Models\AgentLog;
use App\Models\Recharge;
use App\Models\LevelOrder;
use App\Models\UpLog;

class ApiController extends Controller{
    public function notify(Request $req,$orderno){
        $set = Set::getSet('wxpay');
        $pay = new \WxPay($set);
        $result = $pay->handleNotify($req->getContent());
        if (!isset($result['transaction_id'])) return;
        
        if (strpos('A'.$orderno, "SR") == 1) {
            $order = Recharge::where('ordersn',$orderno)->first();
            if(empty($order) || $order->status != 0 || Redis::get('ordersnpaydone'.$orderno)) return "success";
            $order->status = 1;
            $order->transid = $result['transaction_id'];
            $order->save();
            AgentLog::creditPay($order->aid, 2, $order->credit, $order->id);
            return 'success';
        }
        if (strpos('A'.$orderno, "UP") == 1) {
            $order = LevelOrder::where('ordersn',$orderno)->first();
            if(empty($order) || $order->status != 0 || Redis::get('ordersnpaydone'.$orderno)) return "success";
            $order->status = 1;
            $order->save();
            if ($order->aid > 0) {
                $agent = Agent::find($order->aid);
                if ($agent->mid == 0) $agent->mid = $order->mid;
                $agent->level = $order->level;
                $agent->save();
                $paid = $agent->paid;
            }else{
                $m = Mem::find($order->mid);
                $order->aid = Agent::insertGetId(array(
                        'mid'=>$m->id,
                        'paid'=>$m->aid,
                        'level'=>$order->level,
                        'mobile'=>$m->mobile,
                        'createtime'=>time(),
                        'code'=>Agent::getUnicode(),
                ));
                $paid = $m->aid;
            }
            UpLog::createLog($paid, $order->aid, $order->reback);
            return 'success';
        }
        $order = Order::where('ordersn',$orderno)->first();
        if(empty($order) || $order->status != 0 || Redis::get('ordersnpaydone'.$orderno)) return "success";
        Redis::setex('ordersnpaydone'.$orderno,10,1);
        $set = Set::getSet('wxpay');
        $pay = new \WxPay($set);
        $result = $pay->handleNotify($req->getContent());
        if (!isset($result['transaction_id'])) return;
        $order->status = 1;
        $order->transid = $result['transaction_id'];
        $order->save();
        
//         $agent = Agent::find($order->aid);
//         if ($agent->credit < $order->agentprice) {//代理余额不足  退款
//             Order::orderFail($order,'商户额度不足'); 
//             return 'success';
//         }
//         AgentLog::creditPay($agent->id, 1, -$order->agentprice, $order->id);
        
        if ($order->type < 10) {
            $item = FeeItem::where('gid',$order->gid)->where('status',0)->orderBy('costprice');
            if ($order->type == 1 && $order->param) {
                $param = json_decode($order->param,1);
                $item->whereRaw("(extra='' or extra='{$param['type']}')");
            }
            $item = $item->first();
        }else{
            $p = json_decode($order->param,1);
            $item = GoodItem::where('oid',$p['oid'])->where('status',0)->orderBy('costprice')->first();
        }
        if (empty($item)) { //没产品了  挂起
            $order->reset = 1;
            $order->reason = '无渠道';
            $order->save();
        }else{
            $channel = Channel::find($item->cid);
            if ($channel->type == 0 && $order->type == 1) {//好顺电费
                $param = json_decode($order->param,1);
                if ($param['type'] == '南网') $order->nums .= '+'.$param['province'].'+'.$param['cardno'].'+'.$param['city'];
                else $order->nums .= $param['province'].'-'.$param['city'];
            }
            $param = array(
                    'orderno'=>$order->ordersn,
                    'mobile'=>$order->nums,
                    'itemno'=>$item->itemno,
            );
            $res = Channel::channelPost($channel, 'submit', $param);
            if ($res['code'] != 1) {
                $order->reset = 1;
                $order->reason = !isset($res['nocredit']) ? $res['msg'] : '渠道余额不足';
            }else $order->tradeno = $res['transid'];
            $order->cid = $item->cid;
            $order->costprice = $item->costprice;
            $order->save();
        }
        return 'success';
    }
    
    public function channelprice(Request $req){//同步渠道商品
        set_time_limit(0);
        ignore_user_abort(true);
        Channel::updateGoods();
    }
    
    public function channelnotify(Request $req,$type,$ntype){
        return Channel::notify($req, $type, $ntype);
    }
    
    public function wxauth(Request $req){
        $set = Set::getSet('wxpay');
        if ($req->get('code')){
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$set['appid']}&secret={$set['appsecret']}&code={$req->get('code')}&grant_type=authorization_code";
            $res = curPost($url);
            if (!isset($res['openid'])) die('授权失败'.json_encode($res,JSON_UNESCAPED_UNICODE));
            
            $aid = Agent::where('code',base64_decode($req->cookie('superbar_unicode')))->value('id');
            $mem = Mem::where('aid',$aid)->where('openid',$res['openid'])->first();
            if (empty($mem)) {
                $mem = new Mem();
                $mem->aid = $aid;
                $mem->openid = $res['openid'];
                $mem->createtime = time();
            }
            $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$res['access_token']}&openid={$res['openid']}&lang=zh_CN";
            $result = curPost($url);
            $mem->title = $result['nickname'];
            $mem->avatar = $result['headimgurl'];
            $mem->save();
            return redirect("https://".$req->host()."#/pages/user/index")->cookie('superbar_memlastopenid',base64_encode($res['openid']),365*24*3600);
        }
    }
}